const mariadb = require('mariadb');

class OperDatabase{
     constructor(){
        let conn = null;

        this.getConn = function(){
            return conn;
        }

        this.setConn = function( val ){
            conn = val;
        }
    }
    //建立连接
    async connection(  ){
        // multipleStatements: true
        return await  new Promise(function( resolve , reject ){
            mariadb.createConnection({
                host: process.env.NODE_DB_HOST ,
                user: process.env.NODE_DB_USER ,
                password: process.env.NODE_DB_PSD ,
                database: 'fregments' ,
                multipleStatements: true
            })
            .then(conn => {
                resolve( conn );
            })
            .catch(err => {
              //handle connection error
              reject( err );
            });
        });
    }

    //数据查询
    async queryData( sqlString ){
        
        let that = this;
    
        return await new Promise( async function( resolve , reject ){
            // let conn = await that.connection();
            try{
                
            that.setConn( await that.connection());
            //建立链接
            that.getConn().query( sqlString )
            .then(rows => {
                
              resolve(rows);
              that.getConn().end();
            })
            .catch(err => { 
              //handle query error
              console.log("____>: ", err);
              reject(err);
            });

            }catch(err){
               
                reject(err);
            }

        });
        

    }

    disConnectionDb(){   
        this.connector.end();
    }
}

module.exports = OperDatabase;